using DevExpress.XtraEditors;
using DevExpress.XtraPrinting;
using MesProjectWinform.Entity.Request;
using MesProjectWinform.Helper;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Common;
using MesProjectWinform.WareHouse.Helper;
using MesProjectWinform.用户控件;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Forms;

namespace MesProjectWinform.WareHouse.Form.工序排序
{
    public partial class Form_ProcessSort : DevExpress.XtraEditors.XtraForm
    {
        // 分页相关变量
        private int currentPage = 1;
        private int pageSize = 10;
        private int totalRecords = 0;
        private PaginationControl paginationControl;

        public Form_ProcessSort()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form_ProcessSort_Load(object sender, EventArgs e)
        {
            // 初始化分页控件
            InitPaginationControl();

            // 加载初始数据
            LoadData();
        }

        /// <summary>
        /// 初始化分页控件
        /// </summary>
        private void InitPaginationControl()
        {
            // 创建分页控件
            paginationControl = new PaginationControl();
            paginationControl.Dock = DockStyle.Fill;
            paginationControl.PageSize = pageSize;
            paginationControl.CurrentPage = currentPage;
            paginationControl.TotalRecords = totalRecords;

            // 注册分页事件
            paginationControl.PageChanged += PaginationControl_PageChanged;

            // 添加到panelControl3
            panelControl3.Controls.Add(paginationControl);
        }

        /// <summary>
        /// 分页控件页码变更事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PaginationControl_PageChanged(object sender, EventArgs e)
        {
            // 获取新的页码
            currentPage = paginationControl.CurrentPage;

            // 重新加载数据
            LoadData();
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private async void LoadData()
        {
            try
            {
                // 禁用分页控件，防止重复操作
                if (paginationControl != null)
                {
                    paginationControl.Enabled = false;
                }

                // 显示等待光标
                Cursor = Cursors.WaitCursor;

                string action;

                // 对查询参数进行URL编码，避免特殊字符问题
                string encodedCode = Uri.EscapeDataString(TxtCode.Text.Trim());
                string encodedName = Uri.EscapeDataString(TxtName.Text.Trim());
                action = $"WareHouse/Process/GetProcessList?pageNum={currentPage}&pageSize={pageSize}&QryID={encodedCode}&QryName={encodedName}";
                // 调用API
                HttpClientHelper helper = new HttpClientHelper();
                string json = helper.RequestUrlNew(RequestType.Get, action, null);
                ApiPaging<List<ProcessModel>> model = JsonConvert.DeserializeObject<ApiPaging<List<ProcessModel>>>(json);
                
                // 使用安全的UI更新方式
                UpdateUIWithData(model);
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行查询时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                // 确保分页控件可用
                if (paginationControl != null)
                {
                    paginationControl.Enabled = true;
                }
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 使用获取的数据更新UI
        /// </summary>
        private void UpdateUIWithData(ApiPaging<List<ProcessModel>> model)
        {
            try
            {
                // 将数据转换为DataTable
                DataTable dt = DataConverHelper.ToDataTable(model.Data);

                // 线程安全地更新UI
                Action updateUI = () =>
                {
                    try
                    {
                        // 更新数据网格
                        gridControl1.DataSource = dt;

                        // 更新分页控件
                        if (paginationControl != null)
                        {
                            totalRecords = model.TotalCount;
                            paginationControl.TotalRecords = totalRecords;
                            paginationControl.CurrentPage = currentPage;
                            paginationControl.PageSize = pageSize;

                            // 确保分页控件可用
                            paginationControl.Enabled = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("更新UI控件时发生错误：" + ex.Message, "UI更新错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                };

                // 确保在UI线程上更新控件
                if (gridControl1.InvokeRequired)
                {
                    gridControl1.Invoke(updateUI);
                }
                else
                {
                    updateUI();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新UI数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                // 确保分页控件可用
                if (paginationControl != null)
                {
                    if (paginationControl.InvokeRequired)
                    {
                        paginationControl.Invoke(new Action(() => paginationControl.Enabled = true));
                    }
                    else
                    {
                        paginationControl.Enabled = true;
                    }
                }
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        private void BtnQry_Click(object sender, EventArgs e)
        {
            try
            {
                // 重置为第一页
                currentPage = 1;
                if (paginationControl != null)
                {
                    paginationControl.CurrentPage = 1;
                }

                // 加载数据
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            Form_ProcessAdd form = new Form_ProcessAdd();
            form.UpdateType = true;
            if (form.ShowDialog() == DialogResult.OK)
            {
                Clear();
            }
        }

        /// <summary>
        /// 刷新
        /// </summary>
        private void BtnClear_Click(object sender, EventArgs e)
        {
            Clear();
        }

        /// <summary>
        /// 清空条件并重新加载
        /// </summary>
        private void Clear()
        {
            // 清空搜索框
            TxtCode.Text = string.Empty;
            TxtName.Text = string.Empty;

            // 重置页码
            currentPage = 1;
            if (paginationControl != null)
            {
                paginationControl.CurrentPage = 1;
            }

            // 重新加载数据
            LoadData();
        }

        /// <summary>
        /// 导出
        /// </summary>
        private void BtnExport_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建保存对话框
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "Excel文件|*.xlsx|Excel 97-2003|*.xls";
                saveDialog.Title = "导出Excel";
                saveDialog.FileName = "工艺流程信息_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                saveDialog.RestoreDirectory = true;

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    // 显示等待提示
                    Cursor = Cursors.WaitCursor;

                    // 根据文件扩展名选择导出格式
                    string extension = Path.GetExtension(saveDialog.FileName).ToLower();

                    if (extension == ".xlsx")
                    {
                        // 导出为XLSX格式
                        gridControl1.ExportToXlsx(saveDialog.FileName);
                    }
                    else if (extension == ".xls")
                    {
                        // 导出为XLS格式
                        gridControl1.ExportToXls(saveDialog.FileName);
                    }

                    // 恢复光标
                    Cursor = Cursors.Default;

                    // 询问是否打开文件
                    if (MessageBox.Show("导出成功，是否立即打开？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveDialog.FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出Excel时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        private async void Update_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (gridView1.FocusedRowHandle >= 0)
                {
                    // 显示等待光标
                    Cursor = Cursors.WaitCursor;

                    Form_ProcessAdd form = new Form_ProcessAdd();
                    form.UpdateType = false;

                    // 获取当前选中行的数据
                    DataRow row = gridView1.GetFocusedDataRow();

                    try
                    {
                        // 创建ProcessModel对象并填充数据
                        ProcessModel process = new ProcessModel();
                        process.PRId = row["PRId"].ToString();
                        process.PRName = row["PRName"].ToString();
                        process.PRNum = int.Parse(row["PRNum"]?.ToString() ?? "0");
                        process.EmpId = row["EmpId"]?.ToString();
                        process.EMPName = row["EMPName"]?.ToString();
                        process.DepId = row["DepId"]?.ToString();
                        process.DepName = row["DepName"]?.ToString();
                       // process.JobId = row["JobId"]?.ToString();
                        process.Memo = row["Memo"]?.ToString();

                        // 传递ProcessModel对象到编辑窗体
                        form.Current = process;
                        form.processItemList = await ListItem(process.PRId);
                        form.processFileList = await ListFile(process.PRId);
                        // 恢复光标
                        Cursor = Cursors.Default;

                        // 显示编辑窗体
                        if (form.ShowDialog() == DialogResult.OK)
                        {
                            // 编辑成功后刷新数据
                            Clear();
                        }
                    }
                    catch (FormatException fex)
                    {
                        MessageBox.Show("数据格式错误：" + fex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("请先选择要修改的工艺流程", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("修改操作失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 确保光标恢复正常
                Cursor = Cursors.Default;
            }
        }
        /// <summary>
        /// 修改获取工艺工序明细
        /// </summary>
        /// <param name="PRId"></param>
        /// <returns></returns>
        public async Task<List<ProcessItemModel>> ListItem(string PRId)
        {
            try
            {
                HttpClientHelper helper = new HttpClientHelper();
                string action = "WareHouse/Process/GetProcessItemList?PRId=" + PRId;
                // 调用API
                string json = helper.RequestUrlNew(RequestType.Get, action, null);
                ApiResult<List<ProcessItemModel>> model = JsonConvert.DeserializeObject<ApiResult<List<ProcessItemModel>>>(json);

                if (model.Code == ApiEnums.Success)
                {
                    return model.Data;
                }
                else
                {
                    MessageBox.Show(model.Message, "获取工序项目失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return new List<ProcessItemModel>();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取工序项目数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return new List<ProcessItemModel>();
            }
        }

        /// <summary>
        /// 修改获取工艺文件
        /// </summary>
        /// <param name="PRId"></param>
        /// <returns></returns>
        public async Task<List<ProcessFileModel>> ListFile(string PRId)
        {
            try
            {
                HttpClientHelper helper = new HttpClientHelper();
                string action = "WareHouse/Process/GetProcessFileList?PRId=" + PRId;
                // 调用API
                string json = helper.RequestUrlNew(RequestType.Get, action, null);
                ApiResult<List<ProcessFileModel>> model = JsonConvert.DeserializeObject<ApiResult<List<ProcessFileModel>>>(json);

                if (model.Code == ApiEnums.Success)
                {
                    return model.Data;
                }
                else
                {
                    MessageBox.Show(model.Message, "获取工序项目失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return new List<ProcessFileModel>();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取工序项目数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return new List<ProcessFileModel>();
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        private async void Delete_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行的数据
                var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view != null && view.SelectedRowsCount > 0)
                {
                    // 获取当前选中行的工艺流程名称和ID
                    int rowHandle = view.GetSelectedRows()[0];
                    string prId = view.GetRowCellValue(rowHandle, "PRId").ToString();
                    string prName = view.GetRowCellValue(rowHandle, "PRName")?.ToString() ?? "未命名工艺流程";

                    // 显示确认对话框
                    DialogResult result = MessageBox.Show($"确定要删除工艺流程 \"{prName}\" 吗？\n删除后将无法恢复！",
                                                      "删除确认",
                                                      MessageBoxButtons.YesNo,
                                                      MessageBoxIcon.Warning,
                                                      MessageBoxDefaultButton.Button2);

                    // 用户确认删除
                    if (result == DialogResult.Yes)
                    {
                        // 显示正在处理的提示
                        Cursor = Cursors.WaitCursor;
                        List<ProcessFileModel> fileModel =await  ListFile(prId);
                        // 调用删除API
                        string action = "WareHouse/Process/DeleteProcess?processId=" + prId;
                        HttpClientHelper helper = new HttpClientHelper();
                        string json = helper.RequestUrlNew(RequestType.Delete, action, null);
                        ApiResult<int> model = JsonConvert.DeserializeObject<ApiResult<int>>(json);
                        
                        // 如果操作成功，刷新数据
                        if (model.Code == ApiEnums.Success)
                        {
                            foreach (var file in fileModel)
                            {
                                if (!string.IsNullOrEmpty(file.Address))
                                {
                                    // 从七牛云删除文件
                                    bool deleteResult = QiNiuHelper.DeleteFile(file.Address);
                                }
                            }
                            // 重新加载数据
                            LoadData();
                        }
                        else
                        {
                            MessageBox.Show(model.Message, "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        // 恢复光标
                        Cursor = Cursors.Default;
                    }
                }
                else
                {
                    MessageBox.Show("请先选择要删除的工艺流程", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("删除操作失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 序号显示
        /// </summary>
        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        /// <summary>
        /// 查看
        /// </summary>
        private async void View_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (gridView1.FocusedRowHandle >= 0)
                {
                    // 显示等待光标
                    Cursor = Cursors.WaitCursor;

                    // 获取当前选中行的数据
                    DataRow row = gridView1.GetFocusedDataRow();

                    Form_ProcessAdd form = new Form_ProcessAdd();
                    // 设置为查看模式
                    form.UpdateType = false;
                    form.IsViewMode = true;  // 假设Form_ProcessAdd有IsViewMode属性用于控制只读模式

                    try
        {
                        // 创建ProcessModel对象并填充数据
                        ProcessModel process = new ProcessModel();
                        process.PRId = row["PRId"].ToString();
                        process.PRName = row["PRName"].ToString();
                        process.PRNum = int.Parse(row["PRNum"]?.ToString() ?? "0");
                        process.EmpId = row["EmpId"]?.ToString();
                        process.EMPName = row["EMPName"]?.ToString();
                        process.DepId = row["DepId"]?.ToString();
                        process.DepName = row["DepName"]?.ToString();
                        process.Memo = row["Memo"]?.ToString();

                        // 传递ProcessModel对象到查看窗体
                        form.Current = process;

                        // 获取工序项目和文件列表数据
                        form.processItemList = await ListItem(process.PRId);
                        form.processFileList = await ListFile(process.PRId);

                        // 恢复光标
                        Cursor = Cursors.Default;

                        // 显示查看窗体
                        form.ShowDialog();
                    }
                    catch (FormatException fex)
                    {
                        MessageBox.Show("数据格式错误：" + fex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("请先选择要查看的工艺流程", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("查看操作失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 确保光标恢复正常
                Cursor = Cursors.Default;
            }
        }

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            try
            {
                if (gridView1.FocusedRowHandle >= 0)
                {
                    // 显示等待光标
                    Cursor = Cursors.WaitCursor;

                    // 获取当前选中行的PRId
                    string prId = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "PRId")?.ToString();
                    
                    if (!string.IsNullOrEmpty(prId))
                    {
                        // 加载工序项目列表
                        LoadProcessItems(prId);
                    }
                    else
                    {
                        MessageBox.Show("无法获取工艺流程ID", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    // 恢复光标
                    Cursor = Cursors.Default;
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("获取工序项目数据失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载工序项目列表
        /// </summary>
        /// <param name="prId">工艺流程ID</param>
        private async void LoadProcessItems(string prId)
        {
            try
            {
                // 显示等待光标
                Cursor = Cursors.WaitCursor;
                HttpClientHelper helper = new HttpClientHelper();
                // 调用API获取工序项目列表
                string action = "WareHouse/Process/GetProcessItemList?PRId=" + prId;
                string json = helper.RequestUrlNew(RequestType.Get, action, null);
                ApiResult<List<ProcessItemModel>> model = JsonConvert.DeserializeObject<ApiResult<List<ProcessItemModel>>>(json);

                if (model.Code == ApiEnums.Success)
                {
                    // 将数据转换为DataTable
                    DataTable dt = DataConverHelper.ToDataTable(model.Data);

                    // 更新gridView2数据源
                    Action updateUI = () =>
                    {
                        try
                        {
                            gridControl2.DataSource = dt;
                            
                            // 配置gridView2以显示序号
                            gridView2.IndicatorWidth = 40;
                            gridView2.CustomDrawRowIndicator += GridView2_CustomDrawRowIndicator;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("更新工序项目数据时发生错误：" + ex.Message, "UI更新错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    };

                    // 确保在UI线程上更新控件
                    if (gridControl2.InvokeRequired)
                    {
                        gridControl2.Invoke(updateUI);
                    }
                    else
                    {
                        updateUI();
                    }
                }
                else
                {
                    MessageBox.Show(model.Message, "获取工序项目失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载工序项目数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }
        
        /// <summary>
        /// 工序项目列表序号显示
        /// </summary>
        private void GridView2_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
    }
} 